package com.pioneer.cloudstorage.controller;

import com.pioneer.cloudstorage.pojo.entity.Result;
import com.pioneer.cloudstorage.pojo.vo.ResultUpload;
import com.pioneer.cloudstorage.pojo.vo.SearchFileVO;
import com.pioneer.cloudstorage.service.UsersService;
import com.pioneer.cloudstorage.utils.BaseContext;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@Slf4j
public class Search {
    @Autowired
    UsersService usersService;

    /**
     * GET /api/search
     * 智能搜索文件（同时搜索文件名和内容）
     * 查询参数: keyword (必填)
     */
    @GetMapping("/api/search")
    public ResponseEntity<Result> searchFiles(
            @RequestParam String keyword,
            HttpServletRequest request) {

        try {
            Long userId =BaseContext.getCurrentId();

            if (!StringUtils.hasText(keyword)) {
                return ResponseEntity.badRequest()
                        .body(Result.error("搜索关键词不能为空"));
            }

            List<SearchFileVO> results = usersService.searchFiles(userId, keyword);
            log.info("搜索成功，用户: {}, 关键词: {}, 结果数: {}",
                    userId, keyword, results.size());

            return ResponseEntity.ok(Result.success(results));

        } catch (RuntimeException e) {
            log.error("搜索业务异常", e);
            return ResponseEntity.badRequest().body(Result.error(e.getMessage()));
        } catch (Exception e) {
            log.error("搜索系统异常", e);
            return ResponseEntity.badRequest().body(Result.error("搜索失败"));
        }
    }

}

